package com.mh.study.java11.feature;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author meng.han
 * @since 2022-03-10
 */
public class Java11Features {

    public List<String> lines(String multilineString){
        return multilineString.lines()
                .filter(line -> !line.isBlank())
                .map(String::strip)
                .collect(Collectors.toList());
    }

    public String newFileMethods(Path tempDir) throws IOException {
        Path filePath = Files.writeString(Files.createTempFile(tempDir, "demo", ".txt"), "Sample text");
        return Files.readString(filePath);
    }

    public String[] collectionToAnArray(){
        List<String> sampleList = Arrays.asList("Java", "Kotlin");
        return sampleList.toArray(String[]::new);
    }

    public List<String> notPredicateMethod(){
        List<String> sampleList = Arrays.asList("Java", "\n \n", "Kotlin", " ");
        return sampleList.stream()
                .filter(Predicate.not(String::isBlank))
                .collect(Collectors.toList());
    }

    public String localVariableSyntaxForLambda(){
        List<String> sampleList = Arrays.asList("Java", "Kotlin");
        return sampleList.stream()
                .map((@Nonnull var x) -> x.toUpperCase())
                .collect(Collectors.joining(", "));
    }

    public String httpClient() throws IOException, InterruptedException {
        HttpClient httpClient = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .connectTimeout(Duration.ofSeconds(20))
                .build();
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .GET()
                .uri(URI.create("https://www.baidu.com"))
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        return httpResponse.body();
    }

}
